<?php
namespace app\index\controller;
use think\Cache;
use think\Db;
use think\Controller;
use app\common\controller\IdexBaseController;
use app\index\model\UserModel;
use app\index\model\ComplainModel;
use app\index\model\MemberVerifModel;
use app\index\model\AgentModel;
use app\index\model\UnionModel;
use app\index\model\Qianyue;
use app\api\controller\Index;
use app\index\controller\Pay;

class Member extends IdexBaseController
{	
	protected function _initialize() {
	   $type=get_brower_type();
	   $this->assign('browder_type',$type);
       parent::_initialize();
    }
	
	function glj_sysm(){
		return $this->fetch();
	}
	public function hongb_list(){
		$where['user_id']=session('info_user')['id'];
		$where['type']=2;
		$list=db("agent_activegold")->where($where)->order("add_time desc ")->limit("10")->select();
		$this->assign('list',$list);
		return $this->fetch();
	}
	public function card(){
    	//二维码链接
    	$code_url = "http://".$_SERVER['HTTP_HOST']."/index/member/index?fx_id=".session('info_user')['id'];
		$use = db("info_user")->where("openid",session("openid"))->find();
		$this->assign('logo',$use['logo']);
		$this->assign('code_url',$code_url);
		return $this->fetch();
	}
	public function hongb02(){
		$hb=db("agent_activegold")->find(input("m"));
		$url=config('API_DOMAIN')."index/member/hongb03?m=".input("m");
		$this->assign('url',$url);
		$code_url= 'http://www.vshop88.net/code/code.php?url='.urlencode($url).'&margin=1&size=10';
		$this->assign("code_url",$code_url);
		$this->assign('hb',$hb);
		return $this->fetch();
	}
	//红包开页面
	public function hongb03(){
		$hb=db("agent_activegold")->where("id",input("m"))->find();
		if(!$hb){
			echo '访问错误';
			exit;
		}
		$type=get_brower_type();//判断是微信还是支付宝打开
		$redirect=config('API_DOMAIN')."index/member/hongb03?m=".input("m");
		$openid=session("openid");
		if(!$openid){
			if($type==1){
				$auth_code=input("auth_code");
				$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
			}else{
				$auth_code=input("code");
				$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
			}
			if(!$auth_code){
				Header("Location: $url");
				exit;
			}
		}
		if($type==1){//支付宝openid
			$field="alipay_id";
			$pay_type=3;
			if(!$openid){
				$openid=user_ali_id($auth_code);
			}
		}elseif($type==2){//微信openid
			$field="openid";
			$pay_type=2;
			if(!$openid){
				  	$data=user_wx_id1($auth_code);
					$openid=$data['openid'];
			}
		}	
		session('openid',$openid);
		$send_user=db("info_user")->find($hb['user_id']);
		if($openid){
			$w_u[$field]=$openid;
			$user=db('info_user')->where($w_u)->find();
			if(!$user){
				$data[$field]			= $openid;
				$data['level']			= $send_user['id'];
				$data['agency_id1']		= $send_user['agency_id1'];
				$data['agency_id2']		= $send_user['agency_id2'];
				$data['oem_id']			= 1;
				$data['salesman_id']	= $send_user['salesman_id'];
				$data['tj_agent']		= $send_user['tj_agent'];
				$data['tj_pt']			= $send_user['tj_pt'];
				$data['tj_pt1']			= $send_user['tj_pt1'];
				$data['add_time']		= now_time();
				$data['reg_type']		= 3; //红包注册
				$data['member_level']	= "ratio_one";
				$user_id=Db::name('info_user')->insertGetId($data);
			}else{
				$user_id=$user['id'];
			}
			$user=db("info_user")->where("id",$user_id)->find();
			session("info_user",$user);
			//新用户领取奖励金
			if($type==2){
				receive();
			}			
		}
		
		$this->assign('user',$send_user);
		$this->assign('hb',$hb);
		return $this->fetch();
	}
	public function hongb_gq(){
		return $this->fetch();
	}
	//红包领取页面
	public function hongb_page(){
		Db::startTrans();
		$hb_id=input('m');
		$user_id=session('info_user')['id'];
		$hb=db("agent_activegold")->alias("a")->lock(true)->
		join("info_user b","a.user_id=b.id")->field("a.*,b.user_name,b.logo")->
		where("a.id",$hb_id)->find();
		if(!$hb){
			echo '访问页面不存在!!!';
			exit;
		}
		$message="";
		$count=0;//当前领取人数
		$status=1;//红包状态
		if($hb['peoples']>=$hb['user_num']){
			$message="红包已领完";
			Db::rollback();
			$status=0;
		}
		if($hb['sums']>$hb['gold_sum']){
			header("Content-type: text/html; charset=utf-8"); 
			echo '红包已经领完!!!';
			exit;
		}
		if($hb['status']==2){
			$status=0;
		}
		$gold_num=0;//我领取的
		$list=db("agent_activelog")->where("gold_id",$hb_id)->order("add_time desc")->select();
		if($list){//判断我是否已经领取过
			foreach($list as $k){
				if($k['user_id']==$user_id){
					$status=0;
					$gold_num=$k['gold_num'];
					break;
				}
			}
		}
		$hb['sums']=sprintf("%.2f",$hb['sums']);
		if($status==1){
			$result=true;
			//平均红包
			if($hb['hb_type']==1){
				if($hb['user_num']-$hb['peoples']==1){
					$gold_num=$hb['gold_sum']-$hb['sums'];
				}else{
					$gold_num=sprintf("%.2f",$hb['gold_sum']/$hb['user_num']);
				}
				
			}else{
				//如果是最后一个红包用红包总金额减去已经领取的
				if($hb['user_num']-$hb['peoples']==1){
					$up['status']=2;	
					$gold_num=$hb['gold_sum']-$hb['sums'];
				}else{
					$p=$hb['user_num']-$hb['peoples'];
					//当前剩余的
					$belive_sum=sprintf("%.2f",$hb['gold_sum']-$hb['sums']);
					$max=sprintf("%.2f",$belive_sum/$p*3*100);
					$gold_num=rand(1,$max)/100;
					if($gold_num>=$belive_sum||$gold_num==0){
						$gold_num = sprintf("%.2f",$belive_sum/$p*100000/100000);
					}
				}
			}
			$up['peoples']=['exp',"peoples+1"];
			$up['sums']=['exp',"sums+$gold_num"];
			$res=db("agent_activegold")->where("id",$hb_id)->update($up);
			if($res){
				$res=db("info_user")->where("id",$user_id)->setInc('score',$gold_num);
				if($res){
					$res=user_score_change($user_id,12,$gold_num,
					'领取鼓励金红包',0,0);
					if(!$res){
						$result=FALSE;
					}
				}else{
					$result=FALSE;
				}
			}else{
				$result=FALSE;
			}
			
			$res=$this->add_hblog($hb['id'],session("info_user")['id'],session("info_user")['mobile'],$gold_num,session("info_user")['user_name'],session("info_user")['logo']);
			if(!$res){
				$result=FALSE;
			}
		}else{
			$result=false;
		}
		$this->assign('gold_num',$gold_num);
		if($result){
			Db::commit();
		}else{
			Db::rollback();
		}
		$url=config('API_DOMAIN')."index/member/hongb03?m=$hb_id";
		$this->assign("url",$url);
		$this->assign('hb',$hb);
		$this->assign('list',$list);
		$this->assign('count',$hb['peoples']);
		$this->assign('status',$status);
		$this->assign('message',$message);
		return $this->fetch();
	}
	public function add_hblog($gold_id,$user_id,$mobile,$gold_num,$user_name,$logo){
		$type=get_brower_type();
		if($user_name){
			
		}else{
			if($type==1){
			  $user_name='支付宝会员';
			}else{
			  $user_name='微信会员';
			}
		}
		$data['gold_id']=$gold_id;
		$data['user_id']=$user_id;
		$data['mobile']=$mobile;
		$data['gold_num']=$gold_num;
		$data['user_name']=$user_name;
		$data['logo']=$logo?$logo:"/public/static/index/images/member.jpg";
		$data['add_time']=now_time();
		$res=db("agent_activelog")->insert($data);
		return $res;
	}
	//发送红包
	public function send_hb(){
		$info_user = session('info_user');
		$data['type']=2;
		$data['user_id']=$info_user['id'];
		$data['gold_sum']=input("hbmoney");//红包金额
		$data['user_num']=input("hbnums");//红包个数
		$data['hb_type']=input('hbtype');
		$data['add_time']=now_time();
		$data['end_time']=date('Y-m-d H:i:s',strtotime('+1 day'));
		$data['memo']=input('memo')?input('memo'):'[鼓励金红包]可在附近合作商家消费抵现';
		$info_user = db('info_user')->where('id',$info_user['id'])->field('id,operate_pwd,score')->find();
		$pwd=input("pwd");
		if(!$pwd){
			return json(['code'=>403,'msg'=>'操作密码错误']);
		}
		if($info_user['operate_pwd'] != md5_salt($pwd)){
				return json(["code"=>403,'msg'=>'操作密码错误']);
		}
		if($info_user['score']<input('hbmoney')){
			return json(['code'=>400,'msg'=>'鼓励金余额不足']);
		}else{
			$res=db('agent_activegold')->insertGetId($data);
			if($res){
				$res1=db("info_user")->where("id",$info_user['id'])->setDec("score",input("hbmoney"));
				if($res1){
					user_score_change($info_user['id'],11,-input('hbmoney'),
					'发送鼓励金红包',0,0);
					return json(['code'=>200,'msg'=>'操作成功','id'=>$res]);	
				}
			}
			return json(['code'=>400,'msg'=>'操作失败']);
		}
	}
	public function hongb_pin(){
		$info_user = session('info_user');
    	$info_user = db('info_user')->where('id',$info_user['id'])->field('score')->find();
    	$this->assign('info_user',$info_user);
		return  $this->fetch();
	}
	public function hongb_put(){
		$info_user = session('info_user');
    	$info_user = db('info_user')->where('id',$info_user['id'])->field('score')->find();
    	$this->assign('info_user',$info_user);
		return  $this->fetch();
	}
	//鼓励金
	public function glj(){
		$pay = new Pay();
		$pay->get_unionid();
		$info_user = session('info_user');
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
		$logs=db('log_user_score')->where("u_id",$info_user['id'])->order('add_time desc')->limit(10)->select();
		$this->assign("logs",$logs); 
    	$this->assign('info_user',$info_user);
		return  $this->fetch();
	}

	public function glj_list(){
		if($_POST){
			$info_user = session('info_user');
			$where['tj_agent_id']=input("agent_id");
			$where['pt_id']=$info_user['id'];
			$where['order_type']=8;
			$field="message,pt_commission,add_time ";
			$logs=db('log_paylog_copy')->field($field)->where($where)->order('add_time desc')->page(input("page"),10)->select();
			return json(["list"=>$logs]);
		}
		$this->assign('agent_id',input('agent_id'));
		return  $this->fetch();
	}
	//鼓励金
	public function get_scores(){
		$info_user = session('info_user');
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
		$page=1;
		$where['u_id']=$info_user['id'];
		if(input("page")){
			$page=input("page");
		}
		$begin=($page-1)*10;
		
		if(input("score_tp")==1){
			$where['balance']=[">",0];
		}elseif(input("score_tp")==2){
			$where['balance']=["<",0];
		}
		if(input("time_tp")==1){
			$logs=db('log_user_score')->where($where)->whereTime('add_time', 'week')->order('add_time desc')->limit($begin,10)->select();
		}elseif(input("time_tp")==2){
			$logs=db('log_user_score')->where($where)->whereTime('add_time', 'month')->order('add_time desc')->limit($begin,10)->select();
		}else{
			$logs=db('log_user_score')->where($where)->order('add_time desc')->limit($begin,10)->select();
		} 
		return json(["list"=>$logs]);
	}
	//订单付款
	public function pay_order(){
		$order=db('agent_syorder')->field("agent_id,sn,pay_price")->find(input("oid"));
		if(!$order){
			header("Content-type: text/html; charset=utf-8"); 
			echo '无效订单';exit;
		}
		$pay_price=$order['pay_price'];
		$sn=$order['sn'];
		$type=get_brower_type();//判断是微信还是支付宝打开
		$agent=db("info_agent")->field("cb_no,cb_miyao,cb_clerk")->find($order['agent_id']);
		if($type==1){//支付宝
    		$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,1,$sn,'');
			Header("Location: $url");
			exit;
		}elseif ( $type==2 ) {//微信扫码
			$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,2,$sn,'');
			Header("Location: $url");
			exit;
		}else{
			header("Content-type: text/html; charset=utf-8"); 
			echo "请在微信或者支付宝打开";exit;
		} 
	}
	//订单详情
	public function order_page(){
		$order=db("agent_syorder")->alias("a")->
		join("info_agent i","i.id=a.agent_id")->
		join("agent_goods g",'a.goods_id=g.id')->
		where("a.id",input("oid"))->
		field("a.message,a.sn,a.pay_type,a.need_score,a.give_score,g.thumb,a.id,g.goods_name,i.agent_name,a.pay_price,a.add_time,a.status")->find();
		$this->assign('order',$order);
		$hx_url=config("WEB_DOMAIN")."index/member/hexiao?t=3&o=".$order['id'];
		$this->assign('hx_url',$hx_url);
		return  $this->fetch();
	}
	//合伙人推荐的商家
	public function pt_tg(){
		$list=db("info_user")->where("pt_id",session('info_user')['id'])->order()->select();
		return $this->fetch("",["list"=>$list]);
	}
	public function hexiao(){
		$user=session('info_user');
		if(!$user){
			return $this->fetch("hx_error",['msg'=>'您不是会员!']);
		}
		$clerk=db('agent_clerk')->where('user_id',$user['id'])->find();
		if(!$clerk){
			return $this->fetch("hx_error",['msg'=>'您不是本店收银员!']);
		}
		$order=db("agent_syorder")->alias("a")->
		join("agent_goods g",'a.goods_id=g.id')->
		where("a.id",input("o"))->where('a.agent_id',$clerk['agent_id'])->
		field("a.message,a.sn,a.pay_type,a.need_score,a.give_score,g.thumb,a.id,g.goods_name,a.pay_price,a.add_time,a.status")->find();
		$this->assign('order',$order);
		if(!$order){
			return $this->fetch("hx_error",['msg'=>'您不是本店收银员!']);
		}
		if($order['status']!=4){
			return $this->fetch("hx_error",['msg'=>'订单未支付或者已经核销!']);
		}
		$up['hx_time']=now_time();
		$up['hxclerk_id']=$clerk['id'];
		$up['status']=5;
		$res=db("agent_syorder")->where("id",input("o"))->update($up);
		if(!$res){
			return $this->fetch("hx_error",['msg'=>'订单异常无法核销!']);
		}else{
			return $this->fetch("hx_success");
		}
	}
//	public function hx_success(){
//		$order=db("agent_syorder")->alias("a")->
//		join("agent_goods g",'a.goods_id=g.id',"LEFT")->
//		where("a.id",input("o"))->
//		field("a.sn,a.pay_type,a.need_score,a.give_score,g.thumb,a.id,g.goods_name,a.pay_price,a.add_time,a.status")->find();
//		$this->assign('order',$order);
//		return $this->fetch("hx_success");
//	}
	//核销日志
	public function hexiao_logs(){
		$user=session('info_user');
		if(!$user){
			return $this->fetch("hx_error",['msg'=>'您不是会员!']);
		}
		$clerk=db('agent_clerk')->where('user_id',$user['id'])->find();
		if(!$clerk){
			return $this->fetch("hx_error",['msg'=>'您不是本店收银员!']);
		}
		if($_POST){
			$where['agent_id']=$clerk['agent_id'];
			$where['status']=["in",[4,5,6]];
			if(input("score_tp")){
				if(input("score_tp")==4){
					$where['status']=input("score_tp");
				}else{
					$where['status']=["in",[5,6]];
				}
				
			}
			$field="id,sn,hx_time,hxclerk_id,pay_price,need_score,give_score";
			if(input("time_tp")==1){
				$logs=db('agent_syorder')->where($where)->whereTime('add_time', 'today')->field($field)->order('add_time desc')->page(input("page"),10)->select();
				$total=db('agent_syorder')->where($where)->whereTime('add_time', 'today')->field("count(id) c,sum(total_price) s")->find();
			}elseif(input("time_tp")==2){
				$logs=db('agent_syorder')->where($where)->whereTime('add_time', 'month')->field($field)->order('add_time desc')->page(input('page'),10)->select();
				$total=db('agent_syorder')->where($where)->whereTime('add_time', 'month')->field("count(id) c,sum(total_price) s")->find();
			}else{
				$logs=db('agent_syorder')->where($where)->field($field)->order('add_time desc')->page(input('page'),10)->select();
				$total=db('agent_syorder')->where($where)->field("count(id) c,sum(total_price) s")->find();
			}
			return json(["list"=>$logs,"total"=>$total]);
		}
		return $this->fetch();
	}
	//订单评价
	public function comment(){
		if($_POST){
			$data['uid']=session("info_user")['id'];
			$data['user_thumb']=session("info_user")['logo'];
			$data['mobile']=session("info_user")['mobile'];
			$data['rank']=input("score");
			$data['order_id']=input("oid");
			$data['goods_id']=input('goods_id');
			$data['agent_id']=input("agent_id");
			$data['content']=input('content');
			if(input('post.')['imgs']){
				$data['img_url']=implode(",", input('post.')['imgs']);
			}
			$data['add_time']=date('Y-m-d',time());
			$res=db('goods_comment')->insert($data);
			if($res){
				db('agent_syorder')->where("id",input("oid"))->update(["status"=>6]);
				return json(['code'=>200,'msg'=>'评价成功']);
			}else{
				return json(['code'=>400,'msg'=>'评价失败']);
			}
		}else{
			$order=db("agent_syorder")->alias("a")->
			join("agent_goods g",'a.goods_id=g.id')->where("a.id",input("oid"))->
			field("a.agent_id,a.id,a.goods_id,g.goods_name,a.pay_price,a.add_time,a.status")->find();
			$this->assign('order',$order);
		}
		return  $this->fetch();
		
	}
	//订单
	public function orders(){
		$where['a.user_id']=session("info_user")['id'];
		$where['a.type']=4;
		$where['a.status']=['<>',8];
		if(input("status")){
			$where['a.status']=input("status");
			$this->assign('status',input("status"));
		}else{
			$this->assign('status',0);
		}
		$orders=db("agent_syorder")->alias("a")->
		join("info_agent i","i.id=a.agent_id")->
		join("agent_goods g",'a.goods_id=g.id')->where($where)->
		field("i.logo,a.id,g.goods_name,i.agent_name,a.pay_price,a.add_time,a.status")->select();
		$this->assign('orders',$orders);
		return  $this->fetch();
	}
	
	//订单删除
	function up_state(){
		$order_id = input('oid');
		//修改订单信息
		$rest = db('agent_syorder')->where('id',$order_id)->update(['status' => 8]);
		if($rest){
			return json(["code"=>200,'msg'=>'删除成功']);
		}else{
			return json(["code"=>403,'msg'=>'删除失败']);
		}
	}
	
	//购买鼓励金
	public function to_pay(){
		$info_user = session('info_user');
		$ratio=db('user_ratio')->where('id',1)->value($info_user['member_level']);
		$clerk_id=input('clerk_id')?input('clerk_id'):0;
	    $y_type=input('y_type')?input('y_type'):0;
		$agent_id = input('agent_id')?input('agent_id'):0;
	    $cz_much=input("cz");
		$cz_type=1;//鼓励金购买
		if(input("cz_type")){
			$cz_type=input("cz_type");
		}
		if($cz_type==1){
    
			$redirect_url = 'https://'.$_SERVER['HTTP_HOST'].'/index/member/glj';
			
			$type=get_brower_type();//判断是微信还是支付宝打开
			$pay_type=2;
			if($type==1){//支付宝openid
				$pay_type=3;
			}
			$redirect_url 	= $redirect_url.'?fx_id='.$info_user['id'];
			
			if($y_type == 1){
				if($clerk_id){
					$clerk=db('agent_clerk')->where("user_id",$clerk_id)->field("id")->find();
					$cid=$clerk['id'];
					$redirect_url = config("API_DOMAIN")."index/pay/qrcode_pay?clerk_id=$cid";
				}else{
					$redirect_url = config("API_DOMAIN")."index/pay/qrcode_pay?agent_id=$agent_id";					
				}
				
			}
			
			$order_sn = order_create_no(); 
			$rest = recharge_log($info_user['id'], $cz_much, 8, $order_sn, $pay_type, '用户购买鼓励金', config('cut_oem_id'),$clerk_id);
			if($type==1){//支付宝
		        $url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',$cz_much,1,$order_sn,'',$redirect_url);
			}elseif ( $type==2 ) {//微信扫码
				$url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',$cz_much,2,$order_sn,'',$redirect_url);
			}
			Header("Location: $url");
			exit;
		}elseif($cz_type==2){
			$user = db('info_user')->field('mobile')->where('id',$info_user['id'])->find(); 
			if(!$user['mobile']){
				$redirect_url = 'http://'.$_SERVER['HTTP_HOST'].'/index/index/my_mobile';
			}else{
				$redirect_url = 'http://'.$_SERVER['HTTP_HOST'].'/index/member/friends';
			}
			$type=get_brower_type();//判断是微信还是支付宝打开
			$pay_type=2;
			if($type==1){//支付宝openid
				$pay_type=3;
			}
			$redirect_url 	= $redirect_url.'?fx_id='.$info_user['id'];
			
			$order_sn = order_create_no();
			$rest = recharge_log($info_user['id'], $cz_much, 8, $order_sn, $pay_type, '用户购买鼓励金', config('cut_oem_id'),$clerk_id);
			if($type==1){//支付宝
		        $url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',$cz_much,1,$order_sn,'',$redirect_url);
			}elseif ( $type==2 ) {//微信扫码
				$url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',$cz_much,2,$order_sn,'',$redirect_url);
			}
			Header("Location: $url");
			exit;
			
		}elseif($cz_type==3){
			$redirect_url = 'http://'.$_SERVER['HTTP_HOST'].'/index/member/share_erweim';
			
			$type=get_brower_type();//判断是微信还是支付宝打开
			$pay_type=2;
			if($type==1){//支付宝openid
				$pay_type=3;
			}
			$redirect_url 	= $redirect_url.'?fromuid='.$info_user['id'];
			
			$order_sn = order_create_no();
			$rest = recharge_log($info_user['id'], $cz_much, 8, $order_sn, $pay_type, '用户购买鼓励金', config('cut_oem_id'),$clerk_id);
			if($type==1){//支付宝
		        $url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',$cz_much,1,$order_sn,'',$redirect_url);
			}elseif ( $type==2 ) {//微信扫码
				$url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',$cz_much,2,$order_sn,'',$redirect_url);
			}
			Header("Location: $url");
			exit;
		}
		$pay_code_url = 'http://'.$_SERVER['HTTP_HOST'].'/index/member/cz_pay_code?user_id='.$info_user['id']
						.'&user_oem_id='.$info_user['oem_id'].'&cz_much='.$cz_much.'&redirect_url='.$redirect_url.'&y_type='.$y_type.'&agent_id='.$agent_id.'&clerk_id='.$clerk_id;
		$url='http://www.vshop88.net/code/code.php?url='.urlencode($pay_code_url).'&margin=1&size=10';
		$this->assign('cut_url',$pay_code_url);
		$this->assign('much',$cz_much);
		$this->assign('ratio',$ratio);
		return  $this->fetch();
	}
	
	//购买发起支付
	function cz_pay_code(){
		$type=get_brower_type();//判断是微信还是支付宝打开
		$pay_type=2;
		if($type==1){//支付宝openid
			$pay_type=3;
		}
		$user_id 		= input('user_id');
		$user_oem_id 	= input('user_oem_id');
		$cz_much 		= input('cz_much');
		$cz_type 		= input('cz_type');
		$redirect_url 	= input('redirect_url');
		$redirect_url 	= $redirect_url.'?fx_id='.$user_id;
		
		$order_sn = order_create_no();
		recharge_log($user_id, $cz_much, 8, $order_sn, $pay_type, '用户购买鼓励金', $user_oem_id);
		
		if($type==1){//支付宝
			$url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',$cz_much,1,$order_sn,'',$redirect_url);
		}elseif ( $type==2 ) {//微信扫码
			$url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',$cz_much,2,$order_sn,'',$redirect_url);
		}
		Header("Location: $url");
		exit;
	}
	
	
	//购买兑现协议
	public function xieyi(){
		return  $this->fetch();
	}
	public function glj_tixian(){
		$info_user = session('info_user');
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
		if($_POST){
			$much=input("much");//鼓励金转余额10：1
			$pwd = md5_salt(input("pwd"));
			$oem_much=bcmul($much, 0.005, 4);//扣除5%手续费到到龙信平台
			$balance=bcmul ($much,0.095, 4);//
			if($much>$info_user['score']){
				return json(["code"=>400,'msg'=>'鼓励金余额不足']);
			}
			//判断支付密码
			if($pwd != $info_user['operate_pwd']){
				return json(["code"=>401,'msg'=>'密码错误']); 
			}
			
			Db::startTrans();
			$res=user_score_change($info_user['id'],9,-$much,'鼓励金兑换到余额扣除鼓励金');
			if($res){
				$res1=admin_charge($oem_much,1,$info_user['id'],0,'用户鼓励金兑换到余额');
				if($res1){
					$res2=user_money_change($info_user['id'],4,$balance,'鼓励金兑换到余额');
					$sql="update info_user set score=score-$much,balance=balance+$balance,total_income=total_income+$balance where id=".$info_user['id'];
					if($res2){
						$res3=DB::execute($sql);
						if($sql){
							Db::commit();
							return json(["code"=>400,'msg'=>'兑换到余额成功']);
						}
					}
				}
	
			}
			 Db::rollback();
			 return json(["code"=>400,'msg'=>'兑换到余额失败']);
		}
        $where['u_id']= session('info_user')['id'];
		$where['order_type'] =4;
		$balance = Db::table('log_user_charge')->where($where)->whereTime('add_time', 'today')->sum('balance');
		$this->assign('balance',$balance);
    	$this->assign('info_user',$info_user);
		return  $this->fetch();
	}

    //用户鼓励金充值
	public function glj_cz(){ 
		$info_user = session('info_user');
		$info_user = db('info_user')->where('id',$info_user['id'])->find();
        //var_dump($user_ratio);
		//该等级会员的充值比例
		$user_ratio = db('user_ratio')->where('id',1)->value($info_user['member_level']);
		//var_dump($user_ratio);
		$this->assign('user_ratio',$user_ratio);
    	$this->assign('info_user',$info_user);
		
		//鼓励金购买面额
		$glj = db('agent_set_cz')->find();
		// var_dump($glj);
		// exit;
		$this->assign('glj',$glj);
		return  $this->fetch();
	}	
	
	//平台鼓励金充值
	public function agent_glj_cz(){
		$info_user = session('info_user');
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	$this->assign('info_user',$info_user);
    	
    	
    	$agent_set = db('agent_set_cz')->where('agent_id',input('agent_id'))->find();
    	if(!$agent_set){
    		$agent_set['one_money']=10;
			$agent_set['two_money']=50;
			$agent_set['three_money']=100;
    		//$this->redirect(config('API_DOMAIN').'index/member/glj_cz');
    	}
    	$clerk_id=input('clerk_id')?input('clerk_id'):0;
		if($clerk_id){
			$clerk=db('agent_clerk')->where('id',$clerk_id)->field("user_id")->find();
			$clerk_id=$clerk['user_id'];
		}
    	$this->assign('clerk_id',$clerk_id);
    	$y_type = input('y_type')?input('y_type'):0;
    	$this->assign('y_type',$y_type);
    	$this->assign('agent_set',$agent_set);
    	$agent_id = input('agent_id')?input('agent_id'):0;
    	$this->assign('agent_id',$agent_id);
		
		return  $this->fetch();
	}	
	
	//分享二维码
	public function share_erweim(){
		$info_user = session('info_user');
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	if($info_user['is_fx']!=1){
    		$this->redirect('index/member/open_fx?cz_type=3');
    	}
		//二维码链接
    	$code_url="http://".$_SERVER['HTTP_HOST']."/index/index/regist?fx_id=".session('info_user')['id'];
		$this->assign('logo',session('info_user')['logo']);
		$this->assign('code_url',$code_url);
		return  $this->fetch();
	}
	//鼓励金转账
	public function glj_zz(){
		$info_user = session('info_user');
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
		if($_POST){
			$much=input("much");//转账金额
			if($much>$info_user['score']){
				return json(["code"=>400,'msg'=>'鼓励金余额不足']);
			}
			if($much>10000 || $much<100){
				return json(["code"=>401,'msg'=>'鼓励金转账金额区间在100到10000之间']);
			}
			
			$no=input("no");//转账账号
			$user=db("info_user")->where('mobile',$no)->find();
			if(!$user){
				return json(["code"=>402,'msg'=>'转账账号不存在']);
			}
			$operate_pwd=input("pwd");//转账金额
			//检查操作密码
			if($info_user['operate_pwd'] != md5_salt($operate_pwd)){
				return json(["code"=>403,'msg'=>'操作密码错误']);
			}
			Db::startTrans();
			$res=user_score_change($info_user['id'],8,-$much,'鼓励金转账扣除鼓励金',$info_user['id'],$user['id']);
			if($res){
				$sql="update info_user set score=score-$much where id=".$info_user['id'];
				$res1=DB::execute($sql);
				if($res1){
					$res2=user_score_change($user['id'],8,$much*0.95,'鼓励金转账收款',$info_user['id'],$user['id']);
					if($res2){
						$sr=$much*0.95;
						$sql="update info_user set score=score+$sr where id=".$user['id'];
						$res3=DB::execute($sql);
						if($res3){
							$balance=bcmul($much, 0.05, 4);//扣除5%手续费到到龙信平台
							$res4=oem_score_change(8,$balance,'用户鼓励金转账',1);
							if($res4){
								$sql="update info_oem set score=score+$balance where id=1";
								$res5=DB::execute($sql);
								if($res5){
									Db::commit();
									return json(["code"=>200,'msg'=>'转账成功']);
								}
							}
						}
					}
				}		
			}
			Db::rollback();
			return json(["code"=>400,'msg'=>'转账失败']);
		}
    	$this->assign('info_user',$info_user);
		return  $this->fetch();
	}
	public function dianzyhq(){
		return $this->fetch();
	}
	//会员中心
    public function index()
    {
    	$info_user = db('info_user')->where('id',session('info_user')['id'])->find();  
    	if($info_user && $info_user['is_fx'] == 1 && strlen($info_user['mobile'])<2){
    		$this->redirect('index/index/my_mobile');
    	} 
    	
    	$info_user['qianyue_state'] = 0;
    	if($info_user['is_agent'] != 0){
    		//获取商家签约信息
    		$qianyue_info = db('agent_qianyue')->where('user_id',session('info_user')['id'])->find();
    		$info_user['qianyue_state'] = $qianyue_info['state'];
    	}
    	
    	$ow['user_id']=session('info_user')['id'];
		$ow['type']=4;
		$ow['status']=4;
    	$count=db("agent_syorder")->where($ow)->count();
		$this->assign("count",$count);
    	$type=get_brower_type();//判断是微信还是支付宝打开
    	$result = true; 
		if ($type==2 && $info_user['is_atten'] != 1) {
			$result = false;
			//是否关注公众号,关注则修改会员状态
			$result = is_atten($info_user);
		}
		//退还鼓励金红包过期的
		$this->update_gold();
    	$this->assign('info_user',$info_user);
    	$this->assign('is_atten',$result);
       	return  $this->fetch();
    }
	//退还过期红包
	function update_gold(){
		$where['end_time']=["<=",now_time()];
		$where['status']=1;
		$where['user_id']=session("info_user")['id'];
		$field="id,agent_id,user_id,gold_sum,type,sums";
		$where['agent_id']=0;
		$gold=db('agent_activegold')->where($where)->field($field)->select();

		$up['status']=2;
		foreach($gold as $g){
			$believe=$g['gold_sum']-$g['sums'];
			//退还剩余鼓励金
			if($g['type']==2&&$believe>0){//会员
				db("info_user")->where("id",session('info_user')['id'])->setInc("score",$believe);
				user_score_change(session("info_user")['id'],13,$believe,'鼓励金红包退还',0,0);
			}
			db("agent_activegold")->where('id',$g['id'])->update($up);
		}
	}
	function yindao(){
		return $this->fetch();
	}
	function test(){
		$openid=session('openid');
		$appid=config('wxpay_appid');
		$secret=config('wxpay_appsercet');
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";	
		$res=file_get_contents($url);
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		
		$access_token=$array1['access_token'];
		$res=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		if(isset($array1['nickname'])){
			
			echo $array1['unionid'];exit;
			
		}else{
			echo 33;exit;
		}
	}
	/**
	 * 判断用户是否关注过公众号
	 */
	function is_atten($info_user){
		$openid=$info_user['openid'];
		$appid=config('wxpay_appid');
		$secret=config('wxpay_appsercet');
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";	
		$res=file_get_contents($url);
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		
		$access_token=$array1['access_token'];
		$res=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		if(isset($array1['nickname'])){
			if(!$info_user['nickname']){
				$up['nickname']=$array1['nickname'];
			}
			if(!$info_user['logo']){
				$up['logo']=$array1['headimgurl'];	
			}
			if($info_user['is_atten']!=1){
				$up['is_atten']=1;				
			}
			if(!$info_user['unionid']){
				$up['unionid']=$array1['unionid'];				
			}
			if($info_user['member_level']=="ratio_one" || empty($info_user['member_level'])){
				$up['member_level']="ratio_two";				
			}
			if(isset($up)){
				db('info_user')->where('openid',$openid)->update($up);				
			}
			return json(["code"=>200]);
		}else{
			return json(["code"=>400]);
		}
	}
	//获取token
	public function getToken($we_config){
		$cache = cache('access_token');
		if ($cache && $cache['token'] && $cache['expire'] > time()) {
			return $cache['token'];
		}
		/*$appid=$we_config['wxpay_appid'];
		$appsecret=$we_config['wxpay_appsercet'];*/
		$appid=config('wxpay_appid');
		$appsecret=config('wxpay_appsercet');
		$rurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
		$weixin =  file_get_contents($rurl);
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		if($array['access_token']){
			$record = array();
			$record['token'] = $array['access_token'];
			$record['expire'] = time() + 7000;
			cache('access_token', $record, $record['expire']);
			return $array['access_token'];
		}else{
			return json(['code'=>406,'msg'=>'获取微信公众号授权失败！错误代码:'.$array['errcode']]);
		}		
	}
	
	public function step1(){
		$info_user = session('info_user');
		$where['user_id']=$info_user['id'];
		$res=db("agent_qianyue")->where($where)->find();
		$this->assign('qy',$res);
		if($res['state']==1){
			$agent=db("info_agent")->where("user_id",$info_user['id'])->find();
			$this->assign("agent",$agent);
			return  $this->fetch("agent");
		}else{
			return  $this->fetch();			
		}
	}
	public function step2(){
		$agent_type=input("agent_type");
		$info_user = session('info_user');
		$where['user_id']=$info_user['id'];
		$res=db("agent_qianyue")->where($where)->find();
		if($res){
			db("agent_qianyue")->where($where)->update(['agent_type'=>$agent_type]);
		}else{
			$data['user_id']=$info_user['id'];
			$data['agent_type']=$agent_type;
			db("agent_qianyue")->insert($data);
		}
		return  $this->fetch();
	}
	public function step3(){
		$info_user = session('info_user');
		$where['user_id']=$info_user['id'];
		$userinfo=db("info_user")->find($info_user['id']);
		if($_POST){
				$qy=db("agent_qianyue")->where($where)->find();
				$param['agent_name'] 	=input("agent_name1");
				$param['trade_type']	=input("trade_type");
				$param['trade_type2']	=input("trade_type2");
				$param['mobile'] 		= input("contact_tel");
				$param['address'] 		=input("address");
				$param['wechat_no'] 	=input("wechat_no");
				$param['user_id'] 		= $info_user['id'];
	    		$param['level1'] 		= $info_user['level'];
	    		$param['add_time'] 		= now_time();
				$param['effective_time'] = date('Y-m-d H:i:s',strtotime('+1year'));
	    		$param['oem_id'] 		= $info_user['oem_id'];
	    		$param['agency_id1'] 	= $info_user['agency_id1'];
	    		$param['agency_id2'] 	= $info_user['agency_id2'];
	    		$param['salesman_id'] 	= $info_user['salesman_id'];
	    		$param['password']		= md5_salt('123456');
	    		$param['operation_pwd'] = md5_salt('123456');
	    		$agent_model = new AgentModel();
	    		$agent=db("info_agent")->where("user_id",$info_user['id'])->find();
				if(!$agent){
					$result = $agent_model->allowField(true)->save($param);
					if($result){
						$agent=db("info_agent")->where("user_id",$info_user['id'])->find();
						$_POST['agent_id']=$agent['id'];
						db("info_user")
								->where("id",$info_user['id'])
								->update(["is_agent"=>1,'mobile' => input("contact_tel"),'password'=>md5_salt('123456'),'update_time'=>now_time() ]);
					}
				}else{
					$result = $agent_model -> allowField(true)-> save($param,['id' => $agent['id']]);
				}				
				$qianyue=new Qianyue();
				$res=$qianyue->allowField(true)->save($_POST,['user_id'=>$info_user['id']]);
				if($res){
					return json(['code'=>200,'msg'=>'保存成功']);
				}else{
					return json(['code'=>400,'msg'=>'保存失败']);
				}
		}
		$qy=db("agent_qianyue")->where($where)->find();
		if($qy['trade_type2']){
			$type2=db("sys_platform_type")->find($qy['trade_type2']);
			$this->assign('type2',$type2);
		}else{
			$this->assign('type2',null);
		}
		$this->assign('qy',$qy);
		$typelist=db('sys_platform_type')->where('pid',0)->select();
		$this->assign('types',$typelist);	
		return  $this->fetch();
	}
	public function step4(){
		if($_POST){
				$info_user = session('info_user');
				$qianyue=new Qianyue();
				$res=$qianyue->allowField(true)->save($_POST,['user_id'=>$info_user['id']]);
				if($res){
					return json(['code'=>200,'msg'=>'保存成功']);
				}else{
					return json(['code'=>400,'msg'=>'保存失败']);
				}
		}
		$info_user = session('info_user');
		$qy=db('agent_qianyue')->where("user_id",$info_user['id'])->find();
		$this->assign('agent_type',$qy['agent_type']);
		$this->assign('qy',$qy);
		return  $this->fetch();
	}
	public function step5(){
			$info_user = session('info_user');
		if($_POST){
				$qianyue=new Qianyue();
				$res=$qianyue->allowField(true)->save($_POST,['user_id'=>$info_user['id']]);
				if($res){
					return json(['code'=>200,'msg'=>'保存成功']);
				}else{
					return json(['code'=>400,'msg'=>'保存失败']);
				}
		}
		$qy=db('agent_qianyue')->where("user_id",$info_user['id'])->find();
		$this->assign('qy',$qy);
		return  $this->fetch();
	}
	public function upload1(){
		include_once ('././vendor/aliyun-oss-php-sdk/autoload.php');
		$files = $_POST["value"];  
	    $tmp = base64_decode($files);  
	    $fn = time()."_".rand(100000, 999999) . ".jpg";
		$fp = './public/uploads/image/'. $fn;
		$fp1 = 'public/uploads/image/'. $fn;
	    $res=file_put_contents( $fp, $tmp);
		$ossClient = new \OSS\OssClient('LTAIaqGtJ3JDXJvv', 'Q2kTcyepAHX0VOR44OtszVoyOKE8gl', 'oss-cn-shanghai.aliyuncs.com');
		try{
			$res=$ossClient->uploadFile("long3",$fn,$fp1);
			$src='https://long3.oss-cn-shanghai.aliyuncs.com/'.$fn;
			unlink($fp1);
			return json(["code"=>200,'url'=>$src]);
		} catch(OssException $e) {
			return json(["code"=>404,'msg'=>'上传错误']);
		}  
		
	}
	public function step6(){
		$info_user = session('info_user');
		if($_POST){
				$qianyue=new Qianyue();
				$param=$_POST;
				$param['add_time']=now_time();
				$param['state']=2;
				$res=$qianyue->allowField(true)->save($param,['user_id'=>$info_user['id']]);
				db("info_agent")->where("user_id",$info_user['id'])->update(["logo"=>input("door_pic"),"is_state"=>2]);
				if($res){
					//短信开关 1 开  0 关
					if(config('sms_flag')==1){
						$tem_w['title']='申请开店';
						$tem=db("sms_template")->where($tem_w)->find();
						$msg=sendsms($tem['sign_name'],config('send_mobile'),$tem['tid'],'code','有新',1);
						$mess="商户入驻签约须知：  您提交资质后，请注意接听系统客服审核来电，来电号码为：0735-2299199，届时需要您提供官方签约短信验证码，敬请悉知。";
						$msg=sendsms($tem['sign_name'],$info_user['mobile'],$tem['tid'],'code',$mess,1);
					}
					return json(['code'=>200,'msg'=>'提交成功等待审核']);
				}else{
					return json(['code'=>400,'msg'=>'保存失败']);
				}
		}
		$qy=db('agent_qianyue')->where("user_id",$info_user['id'])->find();
		$this->assign('qy',$qy);
		return  $this->fetch();
	}
	public function update_pwd(){
		if($_POST){
			$info_user = session('info_user');
			$where['id']=$info_user['id'];
			$where['password']=md5_salt(input("pwd"));
			$update['password']=md5_salt(input("pwd1"));
    		$res = db('info_user')->where($where)->update($update);
			if($res){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>400,'msg'=>'修改失败']);
			}
		}else{
				return  $this->fetch();
		}
	}
		
	public function update_pwd2(){
		//获取当前用户信息
		$user_id = session('info_user')['id'];
		$type = input('type');
		
    	if(request()->isPost()){
    		$result = check_sendcode($_POST['mobile'], $_POST['verifycode'], '发送成功');

			if($result != 1) { 
				return json(['code'=>401,'msg'=>'验证码错误或过期']);
			}
    		$user_info = db('info_user')->where('id',$user_id)->find();
    		if(!$user_info){
				return json(['code'=>402,'msg'=>'用户异常']);
    		}else{
    			$password = md5_salt($_POST['password']);
    			if(strlen($user_info['mobile']) > 2){
    				if($user_info['mobile'] != $_POST['mobile']){ 
						return json(['code'=>403,'msg'=>'手机号码错误']);
    				}else{
    					$reult = Db::table('info_user')->where('id', $user_info['id'])->update(['operate_pwd'=>$password]);
    				}
    			}else{
    				//跟新用户操作密码和电话号码
    				$reult = Db::table('info_user')
    					->where('id', $user_info['id'])
    					->update(['operate_pwd'=>$password,'mobile'=>$_POST['mobile']]);
						
    			}
    		}
    		if($reult){
    			return json(['code'=>200,'msg'=>'修改成功']);
    		}else{
    			return json(['code'=>400,'msg'=>'修改失败']);
    		}
    	}
    	$user_info = db('info_user')->where('id',$user_id)->find();
		$this->assign('user_info',$user_info);
		
		
		$oem_info = db('info_oem')->where('id',config('cut_oem_id'))->find();
    	$this->assign('oem_info',$oem_info);
    	$this->assign('type',$type);
    	return  $this->fetch();
	}
	//更多设置
	public function more(){
		return  $this->fetch();
	}
	public function about(){
		$hyfw = Db::name('system')->where('name', 'service_config')->find();
		$this->assign('system',$hyfw['value']);
		return  $this->fetch();
	}
	public function help(){
			return  $this->fetch();
	}
	public function help_show(){
			$help_id = request()->param('help_id');
		$detail = db('mall_helps')->where('pid',$help_id)->find();
		$detail['content'] = htmlspecialchars_decode($detail['content']);
		$this->assign('detail',$detail);
       	return  $this->fetch();
	}
	public function get_helps(){
		$auth_rule_list = db('mall_helptype')->order("id asc")->select();
        foreach ($auth_rule_list as $value) {
                $menu[] = $value;
        }
        $menu = !empty($menu) ? array2tree($menu) : [];

		if($menu){
			return json(['code'=>200,"data"=>$menu]);
		}else{
			return json(['code'=>405,"msg"=>'数据错误']);
		}	
	}
	//我的推广会员
    public function tglist(){
    	$info_user = session('info_user');
		if($info_user['is_pt']){
			$list=db('info_user')->where('level|tj_pt',$info_user['id'])->field("id,user_name,mobile,score,logo")->order('add_time desc')->select();
		}else{
			$list=db('info_user')->where('level',$info_user['id'])->field("id,user_name,mobile,score,logo")->order('add_time desc')->select();
		}
    	
		$this->assign('list',$list);
       	return  $this->fetch();
    }
	//我的推广商家
    public function tglist2(){ 
       	return $this->fetch(); 
    }

     public function tglist3(){
     	$page = input('page');
    	$info_user = session('info_user');  
		$field='a.id,a.is_score,ad_score,a.start_time,a.end_time,a.id,a.agent_name,a.add_time,a.logo,a.address';
		$list=db('info_agent')->alias("a")->where("a.city_pt",$info_user['id'])->field($field)->page($page,15)->select();
		foreach($list as $k=>$v){
			$mems=db('info_user')->where("tj_agent",$v['id'])->count();
			$list[$k]['mems']=$mems?$mems:0;
			$comm=db("log_paylog_copy")->where("pt_id",$info_user['id'])->where('tj_agent_id',$v['id'])->sum("pt_commission");
			$list[$k]['pt_comm']=$comm?$comm:0;
		}
	    return  json(["list"=>$list]);
    }

    //会员资料
    public function member()
    {
    	$info_user = session('info_user');
    	
    	if(request()->isPost()){
    		$param=input('post.');
    		$user_model = new UserModel();
    		$param['add_time']	= now_time();
    		$rest=$user_model->where('id',$info_user['id'])->update($param);
    		if($rest){
    			$this->success('修改成功');
			}else{
				$this->error('修改失败');
			}
    	}
    	
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	
    	$this->assign('info_user',$info_user);
       	return  $this->fetch();
    }
 	//会员认证
    public function renzhen()
    {
    	$info_user = session('info_user');
    	if(request()->isPost()){
    		$param=input('post.');
    		$member_verif = new MemberVerifModel();
    		$param['user_id']	= $info_user['id'];
			$wh['user_id']=$info_user['id'];
			$wh['user_type']=1;
    		$verif_info = db('sys_member_verif')->where($wh)->find();
    		if($verif_info){
    			$result = $member_verif -> where($wh) -> update($param);
    		}else{
    			$param['add_time']	= now_time();
    			$param['oem_id']	= $info_user['oem_id'];
    			$result = $member_verif -> allowField(true)-> save($param);
    		}
    		if(config('sms_flag')==1){
	     		$tem_w['title']='用户认证';
				$tem=db("sms_template")->where($tem_w)->find();
				$msg=sendsms($tem['sign_name'],config('send_mobile'),$tem['tid'],'code','');   			
    		}
			
			//更新用户认证状态
			$result = db('info_user')->where('id',$info_user['id']) -> update(['is_verify'=>2,'mobile'=>$param['mobile'],'update_time'=>now_time()]);
			
    		if($result){
    			$this->success('提交成功等待审核');
			}else{
				$this->error('失败');
			}
    	}
    	$user_info = db('info_user')->where('id',$info_user['id'])->find();
    	$verif_info = db('sys_member_verif')->where('user_id',$info_user['id'])->where('user_type',1)->find();
    	$this->assign('verif_info',$verif_info);
    	$this->assign('info_user',$user_info);
       	return  $this->fetch();
    }
    
    
    //会员提现
    public function tixian()
    {
    	//获取用户信息
		$info_user = db('info_user')->where('id',session('info_user')['id'])->find();
		//获取用户认证信息
		$member_verif = Db::table('sys_member_verif')->where('user_type', 1)->where('user_id',$info_user['id'])->find();
		$this->assign('info_user',$info_user);
		$this->assign('member_verif',$member_verif);
		
		if(request()->isPost()){
			
			$result = true;
			// 启动事务
			Db::startTrans();			
			try{
				//用户累计收入
				$user_total_money = db('log_user_charge')
											->where('u_id',$info_user['id'])
											->where('balance','>',0)
											->where('order_type','<>',6)
											->sum('balance');
				//检查累计收入 
				if(bccomp($user_total_money, $info_user['total_income'], 1) != 0){
					return json(['code'=>405,'msg'=>'提交申请失败']);
				}
				//计算用户余额 = 累计收入 - 累计提现金额
				$user_cut_money = bcsub($user_total_money, $info_user['total_withdrawals_money'], 1);
				//检查用户余额 
				if(bccomp($user_cut_money, $info_user['balance'], 1) != 0){
					return json(['code'=>403,'msg'=>'提交申请失败']);
				}
				//检查提现金额，核对余额是否合法
				if(bccomp($info_user['balance'], $_POST['balance'], 1)>=0){
					//计算当前余额
					$cut_balance = bcsub($info_user['balance'], $_POST['balance'], 2);
					//更新用户信息
					$rest1 = db('info_user')->where('id', $info_user['id'])->update(['balance'=>$cut_balance]);
					if(!$rest1) $result = false;
				
					//用户提现，余额变化日志
					$rest2 = user_money_change($info_user['id'],1,-$_POST['balance'],'余额提现');
					if(!$rest2) $result = false;
					
					//提现日志
					$rest3 =withdrawals_log($info_user['id'],2,$_POST['balance'],$_POST['balance'],$rest2);
					if(!$rest3) $result = false;
					
					if($result){
						// 提交事务
	    				Db::commit();
	    				
	    				$tem_w['title']='提现申请';
						$tem=db("sms_template")->where($tem_w)->find();
						$msg=sendsms($tem['sign_name'],config('send_mobile'),$tem['tid'],'code','');
						
						return json(['code'=>200,'msg'=>'提交成功']);
					}else{
						//回滚
			    		Db::rollback();
						return json(['code'=>402,'msg'=>'提交失败']);
					}
				}else{
					return json(['code'=>403,'msg'=>'提交失败']);
				}
			}catch ( Exception $e ) {
			    //$e->getMessage();
			    //回滚
			    Db::rollback();
			    exit;
			}
		}
        $where['u_id']= session('info_user')['id'];
		$where['order_type'] =1;
		$balance = Db::table('log_user_charge')->where($where)->whereTime('add_time', 'today')->sum('balance');
		$this->assign('balance',$balance);
      	return  $this->fetch();
    }
    
    
    //商家申请
    public function shenqing()
    {
    	$info_user = session('info_user');
    	
    	//获取用户详细信息
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	
    	if(request()->isPost()){
    		$param=input('post.');
    		$param['user_id'] 		= $info_user['id'];
    		$param['level1'] 		= $info_user['level'];
    		$param['add_time'] 		= now_time();
    		$param['oem_id'] 		= $info_user['oem_id'];
    		$param['agency_id1'] 	= $info_user['agency_id1'];
    		$param['agency_id2'] 	= $info_user['agency_id2'];
    		$param['salesman_id'] 	= $info_user['salesman_id'];
    		$param['password']		= md5_salt($param['password']);
    		$param['operation_pwd'] = md5_salt($param['operation_pwd']);
    		$agent_model = new AgentModel();
    		$result = $agent_model -> allowField(true)-> save($param);
    		if($result){
    			
    			//更新用户开店状态
    			Db::table('info_user')->where('id', $info_user['id'])->update(['is_agent' => 1]);
    			$this->success('申请成功');
			}else{
				$this->error('申请失败');
			}
    	}
    	
        return  $this->fetch();
    }
    
    //联盟商圈
    public function union()
    {
    	$info_user = session('info_user');
    	
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	
    	//查找当前用户是否已创建联盟
    	$union_agent =  db('union_agent')
    					->where('u_id',$info_user['id'])
    					->where('is_state',1)
    					->find();
    	if($union_agent){
    		$union_agent['is_create'] =1;
    		$this->assign('data',$union_agent);
    	}
    	if(request()->isPost()){
    		$param=input('post.');
    		$union_model = new UnionModel();
    		if($union_agent){
    			$result = $union_model -> allowField(true)->where('u_id',$info_user['id'])-> update($param);
    		}else{
    			$param['add_time'] 	= now_time();
    			$param['oem_id'] 	= $info_user['oem_id'];
    			$param['u_id'] 		= $info_user['id'];
    			$result = $union_model -> allowField(true)-> save($param);
    		}
    		if($result){
    			$this->success('成功');
			}else{
				$this->error('失败');
			}
    	}
    	return  $this->fetch();
    }
    
    
    //联盟成员
    public function union_memberlist()
    {
    	$where['u_id'] 	=  session('info_user')['id'];
    	$where['state'] =  ['in','1,2'];
    	$memberlist = db('union_member')->where($where)->select();
    	$this->assign('memberlist',$memberlist);
    	$this->assign('empty','<span class="empty">没有数据</span>');
        return  $this->fetch();
    }
    //移除成员
    public function yichu()
    {
    	$result = db('union_member')->where('id',input('id'))->delete();
    	if($result){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }
    //审核成员
    public function membershenhe()
    {
    	$param['state'] = 1;
    	$result = db('union_member')->where('id',input('id'))->update($param);
    	if($result){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }
    //积分记录
    public function score_record()
    {
    	$where['u_id'] 	=  session('info_user')['id'];
    	$loglist = db('log_user_score')->where($where)->order("add_time desc")->paginate(20);
    	$this->assign('loglist',$loglist);
    	$this->assign('empty','<span class="empty">没有数据</span>');
        return  $this->fetch();
    }
    
    
    //佣金记录
    public function yongj_record()
    {
    	$where['u_id'] 	=  session('info_user')['id'];
    	$loglist = db('log_user_commission')->where($where)->paginate(20);
    	$this->assign('loglist',$loglist);
    	$this->assign('empty','<span class="empty">没有数据</span>');
        return  $this->fetch();
    }
    
    
    //余额记录
    public function yue_record()
    {
        return  $this->fetch();
    }
	
	public function yuelist()
	{
		$page = input('page');
		$where['u_id'] 	=  session('info_user')['id'];
    	$loglist = db('log_user_charge')->where($where)->order('add_time desc')->page($page,15)->select();
		return  json(["list"=>$loglist]);
	}
    //佣金转余额
    public function yongj_yue()
    {
    	
    	$info_user = db('info_user')->where('id',session('info_user')['id'])->find();
    	
    	if(request()->isPost()){
    		// 启动事务
			Db::startTrans();
			try{
				//查询余额
				if(bccomp($info_user['commission'], $_POST['commission'], 4)>=0){
					//计算佣金转为余额的金额
					$change_val = bcsub($_POST['commission'], bcmul($_POST['commission'], 0.05, 4), 4);
					
					$new_commission = bcsub($info_user['commission'], $_POST['commission'], 4);
					$new_balance = bcadd($info_user['balance'],$change_val, 4);
					//更新用户信息
					db('info_user')->where('id', $info_user['id'])->update(['balance' => $new_balance,'commission'=>$new_commission]);
					//用户佣金变化日志
					user_commission_change($info_user['id'],0,5,$_POST['commission'],2,"佣金转余额扣除佣金",
					0,$info_user['oem_id'],$info_user['agency_id1'],$info_user['agency_id2']);
					//用户余额变化日志
					 user_money_change($info_user['id'],0,2,$change_val,1,"佣金转余额增加余额",
					 0,$info_user['oem_id'],$info_user['agency_id1'],$info_user['agency_id2']);
					// 提交事务
    				Db::commit();
					return json(['code'=>200,'msg'=>'提交成功']);
				}else{
					return json(['code'=>402,'msg'=>'提交失败']);
				}
			}catch ( Exception $e ) {
			    //$e->getMessage();
			    //回滚
			    Db::rollback();
			    exit;
			}
    	}
    	$this->assign('info_user',$info_user);
       	return  $this->fetch();
    }
    //意见反馈
    public function feedback()
    {
    	$info_user = session('info_user');
    	
    	if(request()->isPost()){
    		$param=input('post.');
    		
    		$sys_complain = new ComplainModel();
    		
    		$param['add_time'] = now_time();
    		$param['oem_id'] = $info_user['oem_id'];
    		
    		$rest=$sys_complain->allowField(true)->save($param);
    		if($rest){
    			$this->success('提交成功','index/member/index');
			}else{
				$this->error('提交失败');
			}
    	}
    	
       return  $this->fetch();
    }
    //推广中心
    public function friends()
    {
    	if(request()->isPost()){
    		$user_id = input('user_id');
    		$data['mems']=db("info_user")->where('level',$user_id)->count(); 
			$w["u_id"]=$user_id;
			$w['order_type']=["in",[1,2]]; 
			$data['total_sr']=db("log_user_charge")->where($w)->sum("balance");
			return json(["data"=>$data]);
    	}
       	return  $this->fetch();
    }
    
    public function yaoq()
	{
		$cz_type=2;
		if(input("cz_type")){
			$cz_type=input("cz_type");
		}
		$this->assign('cz_type',$cz_type); 
		return $this->fetch();
	}
     //积分购买
    public function charge_score()
    {
    	$user_info = session('info_user');
    	
    	$user_info = db('info_user')->where($user_info)->find();
    	
		$agent_info = db('info_agent')->where('user_id',$user_info['id'])->find();
		
		$agent_info['score'] = substr($agent_info['score'],0,4);
		
		$this->assign('user_info',$user_info);
    	$this->assign('agent_info',$agent_info);
    	
       return  $this->fetch();
    }
    
     //邀请商家入驻
    public function yaoqsjrz()
    {
    	//查找当前用户是否已创建联盟
    	$union_agent =  db('union_agent')
    					->where('u_id',session('info_user')['id'])
    					->where('is_state',1)
    					->where('state',2)
    					->find();
		    	
    	$this->assign('union_agent',$union_agent);
    	//二维码链接
    	$redirect_url="http://".$_SERVER['HTTP_HOST']."/index/member/union_join?union_id=".
    	$union_agent['id'];
    	
    	$union_agent['redirect_url'] = $redirect_url;
    	
    	$this->assign('union_agent',$union_agent);
    	
    	
       return  $this->fetch();
    }
    
    //商家入驻
    function union_join(){
    	
    	$union_agent =  db('union_agent')->where('id',input('union_id'))->find();
		
		$this->assign('union_agent',$union_agent);
		    	
    	return  $this->fetch();
    }
    
    //分享赚钱
    public function share_money()
    {
    	$user_info = session('info_user');
    	//获取当前用户信息
		$user_info = db('info_user')->where('id',$user_info['id'])->find();    	
    	$this->assign('user_info',$user_info);
       	return  $this->fetch();
    }
    
    //申请加入联盟商圈
    function add_union(){
    	$user_info = session('info_user');
    	//检查当前用户是否是商家
    	$agent_info = db('info_agent')->where('user_id',$user_info['id'])->find();
    	if($agent_info){
    		$union=Db::table('union_agent')->where('id',input('union_id'))->find();
    		$param['u_id']				= $agent_info['user_id'];
    		$param['union_id']			= $union['id'];
    		$param['agent_id']			= $agent_info['id'];
    		$param['store_name']		= $agent_info['agent_name'];
    		$param['thumb']				= $agent_info['logo'];
    		$param['lm_name']			= $union['name'];
    		$param['store_tel']			= $agent_info['mobile'];
    		$param['address']			= $agent_info['address'];
    		$param['customer_volume']	= 0;
    		$param['unnion_ads_money']	= 0.2;
    		$param['add_time']			= now_time();
    		$res = Db::table('union_member')->insert($param);
			if($res){
				return json(['code'=>200,'msg'=>'成功']);
			}else{
				return json(['code'=>403,'msg'=>'失败']);
			}
    	}else{
    		return json(['code'=>402,'msg'=>'请先申请成为商家']);
    	}
    }
    function open_fx(){
    	$info_user = session('info_user');
		$cz_type=2;
		if(input("cz_type")){
			$cz_type=input("cz_type");
		}
		$this->assign('cz_type',$cz_type);
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	$this->assign('info_user',$info_user);
		
		return  $this->fetch();	
    }
    
    //暂无数据
    function none_style(){
    	return  $this->fetch();	
    }
	
	public function get_trades(){
		$data=db('sys_platform_type')->where('pid',input("trade_id"))->select();
		return json(["data"=>$data]);
	}
	
	function confirm_pay(){
		$order_info = db('agent_syorder')
							->where('id',input('order_id'))
							->where('user_id',session('info_user')['id'])
							->find();
		if($order_info){
			$resutl = db('agent_syorder')->where('id',$order_info['id'])->update(['status'=>5]);
			
			if($resutl){
				return json(['code'=>200,'msg'=>'确认成功']);
			}else{
				return json(['code'=>403,'msg'=>'确认失败']);
			}
		}else{
			return json(['code'=>403,'msg'=>'数据异常，订单不存在']);
		}
	}
	
	//登陆
    public function login()
    {
    	if(request()->isPost()){
    		$where['mobile'] 	= input('phone');
    		$where['password'] 	= md5_salt(input('pwd'));
    		$where['is_atten']	= 1;
    		$where['status'] 	= 1;
    		$user_info = db('info_user')->where($where)->find();
    		
    		if($user_info){
    			session('info_user',$user_info);
				if($user_info['is_agent']==2){
					$agent=db("info_agent")->field("id")->where("user_id",$user_info['id'])->find();
					session("agent_id",$agent['id']);
				}
				return json(['code'=>200,'msg'=>'登录成功']);
			}else{
				return json(['code'=>403,'msg'=>'登录失败']);
			}
    	}
       return  $this->fetch();
    }
	
	public function contact(){
    	if (Cache::has('contact_config')) {
            $site_config = Cache::get('contact_config');
        } else {
            $site_config = Db::name('tg_admin_system')->field('value')->where('name', 'contact_config')->find();
            $site_config = unserialize($site_config['value']);
        }
		$this->assign('contact_config',$site_config);
		return  $this->fetch();
	}
	
	public function agentsq(){
		$info_user = session('info_user');
		
		$user_info = db('info_user')->where("id",$info_user['id'])->find();
		if($user_info['is_agent']==2){		
			return  $this->redirect('/store/agent');	
		}
		
		if($_POST){
			$param=input('post.'); 
			
		    if(!$user_info['mobile']){
		    	
            	$result = check_sendcode($param['contact_tel'], $param['yzm'], '发送成功'); 
				if($result != 1) {
					$this->error('验证码错误或过期');
				}			
            }		
			unset($_POST['yzm']);
			$qy = db("agent_qianyue")->where('user_id',$info_user['id'])->find();
			if($qy){
				$_POST['state'] = 2;
				
				$res = db("agent_qianyue")->where('id',$_POST['id'])->update($_POST);
			}else{
				$_POST['user_id'] = $info_user['id'];
				$_POST['state'] = 2;
				$_POST['add_time'] = now_time();
				$res = db("agent_qianyue")->insert($_POST);
			}
			
			if(!$user_info['mobile']){ 
				//更新用户认证状态
			    $result = db('info_user')->where('id',$info_user['id']) -> update(['mobile'=>$param['contact_tel'],'update_time'=>now_time()]);
				
			}
			
			if($res){
				return json(['code'=>200,'msg'=>'提交成功']);
				//短信开关 1 开  0 关
				if(config('sms_flag')==1){
					$tem_w['title']='申请开店';
					$tem=db("sms_template")->where($tem_w)->find();
					$msg=sendsms($tem['sign_name'],config('send_mobile'),$tem['tid'],'code','有新',1);
					$mess="商户入驻签约须知：  您提交信息后，请注意接听系统客服审核来电，来电号码为：0735-2299199，敬请悉知。";
					$msg=sendsms($tem['sign_name'],$info_user['mobile'],$tem['tid'],'code',$mess,1);
				} 
			}else{
				return json(['code'=>400,'msg'=>'提交失败']);
			}
		}
		$qy=db('agent_qianyue')->where("user_id",$info_user['id'])->find();
		$this->assign('mobile',$user_info['mobile']);
		$this->assign('qy',$qy);
		return  $this->fetch();
	}

	public function agent(){	
		$agent = db('info_agent')->where("user_id",session('info_user')['id'])->find();
		$this->assign('agent',$agent);
		return  $this->fetch();
	}
	
	//设置
    public function edit()
	{
		$info_user = db('info_user')->where('id',session('info_user')['id'])->value('mobile');
		$type = $info_user?1:0;
		$this->assign('type',$type);
		return $this->fetch();
	}
	
	//谦穗账号注册
	public function zc()
	{
		$info_user = db('info_user')->where('id',session('info_user')['id'])->field('status,sex,mobile')->find();
		$this->assign('user',$info_user);
		
		if(request()->isPost()){
			//验证验证码是否错误，过期
			$result = check_sendcode($_POST['mobile'], $_POST['yzm'], '发送成功'); 
			if($result != 1) {
				return json(['code'=>400,"msg"=>'验证码错误或过期']);
			} 
			
			if($info_user['status'] == 2){
				return json(['code'=>400,"msg"=>'账号异常']);
			}
			 
			//判断账号是否已经注册
			$mem = db('member')->where('mobile',$_POST['mobile'])->find();
			if($mem){
				return json(['code'=>400,"msg"=>'账号已注册']);
			}else{
				$data['mobile'] = $_POST['mobile'];
				$data['password'] = md5_salt($_POST['password']);
				$data['uid'] = session('info_user')['id'];
				$data['add_time'] = now_time(); 
				$res = db('member')->insert($data);
				if($res){
					return json(['code'=>200,"msg"=>'注册成功']);
				}else{
					return json(['code'=>400,"msg"=>'注册失败']);
				}
			}
		}
		return $this->fetch();
	}

    //用户注册
    public function userzc()
	{ 
		if(request()->isPost()){
			$info_user = db('info_user')->where('mobile',$_POST['mobile'])->field('status,mobile')->find();
			//验证验证码是否错误，过期
			$result = check_sendcode($_POST['mobile'], $_POST['yzm'], '发送成功'); 
			if($result != 1) {
				return json(['code'=>400,"msg"=>'验证码错误或过期']);
			} 
			
			if($info_user['status'] == 2){
				return json(['code'=>400,"msg"=>'账号异常']);
			}
			 
			//判断账号是否已经注册 
			if($info_user){
				return json(['code'=>400,"msg"=>'账号已注册']);
			}else{
				$data['mobile'] = $_POST['mobile'];  
				$data['add_time'] = now_time(); 
				$res = db('info_user')->where('id',session('info_user')['id'])->update($data);
				$user=session("info_user");
				$user['mobile']=$_POST['mobile'];
				session('info_user',$user);
				if($res){
					return json(['code'=>200,"msg"=>'注册成功']);
				}else{
					return json(['code'=>400,"msg"=>'注册失败']);
				}
			}
		} 
	} 
	
	//用户鼓励金详情
	public function tginfo()
	{
		 if(request()->isPOST()){  
			$page=1;
			$where['u_id']=input('id');
			if(input("page")){
				$page=input("page");
			}
			$begin=($page-1)*10;
			
			if(input("score_tp")==1){
				$where['balance']=[">",0];
			}elseif(input("score_tp")==2){
				$where['balance']=["<",0];
			}
			if(input("time_tp")==1){
				$logs=db('log_user_score')->where($where)->whereTime('add_time', 'week')->order('add_time desc')->limit($begin,10)->select();
			}elseif(input("time_tp")==2){
				$logs=db('log_user_score')->where($where)->whereTime('add_time', 'month')->order('add_time desc')->limit($begin,10)->select();
			}else{
				$logs=db('log_user_score')->where($where)->order('add_time desc')->limit($begin,10)->select();
			}  
			return json(["list"=>$logs]);
		 } 
    	$this->assign('score',input('score'));
		$this->assign('id',input('id'));
		return $this->fetch();
	}
	
	public function receive(){
		receive();
	}	
}
